//--------------------------------------------------------------------------
// $Id: Utils.java 4 2006-08-20 18:34:48Z zendragon $
//--------------------------------------------------------------------------
// Copyright 2006 Social Brain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//--------------------------------------------------------------------------

package org.socialbrain.openid;

import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Pattern;

/**
 * @author <a href="http://erning.net/">Zhang Erning</a>
 * @version $Id: Utils.java 4 2006-08-20 18:34:48Z zendragon $
 */
public class Utils
{
    public static String normalizeIdentifier(String identifier)
    {
        identifier = StringUtils.trim(identifier);
        return isXRI(identifier) || isHTTP(identifier)
                ? identifier
                : "http://" + identifier;
    }

    public static boolean isXRI(String identifier)
    {
        return XRI_PATTERN.matcher(identifier).find();
    }

    public static boolean isHTTP(String identifier)
    {
        return HTTP_PATTERN.matcher(identifier).find();
    }

    private static final Pattern XRI_PATTERN = Pattern.compile("^xri://", Pattern.CASE_INSENSITIVE);
    private static final Pattern HTTP_PATTERN = Pattern.compile("^http[s]?://", Pattern.CASE_INSENSITIVE);

    public static String readStringFromStream(InputStream stream, long contentLength, String charset)
            throws IOException
    {
        int size = (contentLength < 0 || contentLength > Constants.MAX_HTML_SIZE)
                ? Constants.MAX_HTML_SIZE
                : (int)contentLength;

        byte[] buffer = new byte[size];
        int readLength = stream.read(buffer);
        return new String(buffer, 0, readLength, charset == null ? Constants.DEFAULT_CHARSET : charset);
    }

    public static String appendQueryString(String url, String qs) throws MalformedURLException
    {
        URL u = new URL(url);
        String query = u.getQuery();
        return query == null
                ? url + "?" + qs
                : url + "&" + qs;
    }
}
